﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Coravel;
using Microsoft.Extensions.DependencyInjection;

namespace ESoft.Job
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class ServiceExt
    {
        /// <summary>
        /// 注册任务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        public static void AddJob(this IServiceCollection services, params Assembly[] assemblies)
        {
            services.AddScheduler();
            Type baseType = typeof(IJob);

            
            Type[] mapperTypes = assemblies.SelectMany(assembly => assembly.GetTypes())
                .Where(type => baseType.IsAssignableFrom(type) && type != baseType && !type.IsAbstract).ToArray();
            foreach (Type type in mapperTypes)
            {
                services.AddSingleton(baseType, type);
            }
            services.AddSingleton<IJobService, JobService>();
        }

        /// <summary>
        /// 启用任务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        public static void UseJob(this IServiceProvider services, params Assembly[] assemblies)
        {
            var jobs = services.GetServices<IJob>();

            if (jobs.Any())
            {
                IJobService jobService = services.GetRequiredService<IJobService>();
              
                jobService.StartupJobs(jobs, assemblies);
            }
        }
    }
}
